import React, { useState } from 'react';
import { AlertCircle } from 'lucide-react';
import { TextInput } from '../components/shared/ModelOptions';

const color_map = {
  // 金融实体类型
  'COMPANY': "#FF0000", // 鲜红 - 企业名称
  'POSITION': "#00FF00", // 鲜绿 - 职位
  'PRODUCT': "#0000FF", // 蓝色 - 金融产品
  'MARKET': "#FFA500", // 橙色 - 市场
  
  // 金融交易相关实体
  '交易号': "#FF1493", // 深粉红
  '订单号': "#9370DB", // 中等紫色
  '资损金额': "#2E8B57", // 海洋绿
  '银行卡号': "#6A5ACD", // 石板蓝
  '支付渠道': "#9932CC", // 深兰花紫
  
  // 相关方实体
  '受害人': "#8B4513", // 棕土色
  '受害人身份': "#A0522D", // 赭石色
  '嫌疑人': "#CD5C5C", // 印第安红
  
  // 时间地点
  '案发城市': "#4682B4", // 钢青色
  '案发时间': "#008B8B", // 深青色
  '涉案平台': "#483D8B", // 深岩蓝
  '手机号': "#4B0082", // 靛青色
  
  // 其他类型
  'DATE': "#FF9800", 
  'TIME': "#673AB7", 
  'PERCENT': "#3F51B5", 
  'MONEY': "#2196F3", 
  'PERSON': "#009688", 
  'ORGANIZATION': "#4CAF50", 
  'NUMBER': "#8BC34A", 
  'INDUSTRY': "#FF5722", 
};

const FinanceNERPage = () => {
  const [input, setInput] = useState('');
  const [result, setResult] = useState('');
  const [coloredResult, setColoredResult] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [termTypes, setTermTypes] = useState({
    tradeNum: false,
    orderNum: false,
    lossAmount: false,
    bankCardNum: false,
    payChannel: false,
    victim: false,
    victimIdentity: false,
    suspect: false,
    caseCity: false,
    caseTime: false,
    casePlatform: false,
    phoneNum: false,
    allFinanceTerms: false,
  });
  const [options, setOptions] = useState({});

  const handleTermTypeChange = (e) => {
    const { name, checked } = e.target;
    if (name === 'allFinanceTerms') {
      setTermTypes({
        tradeNum: false,
        orderNum: false,
        lossAmount: false,
        bankCardNum: false,
        payChannel: false,
        victim: false,
        victimIdentity: false,
        suspect: false,
        caseCity: false,
        caseTime: false,
        casePlatform: false,
        phoneNum: false,
        allFinanceTerms: checked,
      });
    } else {
      setTermTypes({ ...termTypes, [name]: checked });
    }
  };

  const handleOptionChange = (e) => {
    setOptions({ ...options, [e.target.name]: e.target.checked });
  };

  const handleSubmit = async () => {
    setIsLoading(true);
    try {
      const response = await fetch('http://10.128.4.197:8000/api/finance-ner', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ text: input, options, termTypes }),
      });
      const data = await response.json();
      setResult(JSON.stringify(data, null, 2));
      setColoredResult(generateColoredResult(data.text, data.entities));
    } catch (error) {
      console.error('Error:', error);
      setResult('处理请求时发生错误。');
      setColoredResult('');
    }
    setIsLoading(false);
  };

  const generateColoredResult = (text, entities) => {
    // 对实体按位置排序，从后到前处理，避免位置偏移
    const sortedEntities = [...entities].sort((a, b) => b.start - a.start);
    
    // 创建一个React元素数组
    let parts = [];
    let lastEnd = text.length;
    
    // 从后向前遍历实体，构建React元素数组
    for (const entity of sortedEntities) {
      // 添加实体后面的文本
      if (entity.end < lastEnd) {
        parts.unshift(text.slice(entity.end, lastEnd));
      }
      
      // 添加带样式的实体
      const color = color_map[entity.entity_group] || '#000000';
      // 计算文本颜色（深色背景用白色文本，浅色背景用黑色文本）
      const textColor = isLightColor(color) ? '#000000' : '#FFFFFF';
      
      const styledEntity = (
        <span 
          key={`${entity.start}-${entity.end}`}
          style={{
            backgroundColor: color,
            padding: '2px 5px', // 增加水平内边距
            margin: '0 3px',    // 增加实体之间的边距
            borderRadius: '3px',
            position: 'relative',
            display: 'inline-block', // 使用inline-block以便于添加边距
            color: textColor,        // 根据背景色调整文本颜色
            fontWeight: '500',       // 加粗以提高可读性
            verticalAlign: 'baseline',
            boxShadow: '0 1px 2px rgba(0,0,0,0.2)', // 添加阴影增强视觉层次
          }}
        >
          {entity.word}
          <sub style={{ 
            fontSize: '0.75em', 
            marginLeft: '3px',
            color: textColor,
            opacity: 0.9,
            textShadow: '0px 0px 1px rgba(0,0,0,0.3)'
          }}>
            {entity.entity_group}
          </sub>
        </span>
      );
      parts.unshift(styledEntity);
      
      // 更新lastEnd
      lastEnd = entity.start;
    }
    
    // 添加第一个实体前的文本
    if (lastEnd > 0) {
      parts.unshift(text.slice(0, lastEnd));
    }
    
    return parts;
  };
  
  // 判断颜色是否为浅色
  const isLightColor = (hexColor) => {
    // 移除#号
    const hex = hexColor.replace('#', '');
    
    // 将十六进制转换为RGB
    const r = parseInt(hex.substring(0, 2), 16);
    const g = parseInt(hex.substring(2, 4), 16);
    const b = parseInt(hex.substring(4, 6), 16);
    
    // 计算亮度 (HSP方法)
    const brightness = Math.sqrt(
      0.299 * (r * r) + 
      0.587 * (g * g) + 
      0.114 * (b * b)
    );
    
    // 返回是否为浅色 (亮度 > 128 认为是浅色)
    return brightness > 128;
  };

  return (
    <div className="max-w-2xl mx-auto">
      <h1 className="text-3xl font-bold mb-6">金融命名实体识别 💹</h1>
      <div className="bg-white shadow-md rounded-lg p-6 mb-6">
        <h2 className="text-xl font-semibold mb-4">输入金融文本</h2>
        <TextInput
          value={input}
          onChange={(e) => setInput(e.target.value)}
          rows={4}
          placeholder="请输入需要进行命名实体识别的金融文本..."
        />
        
        <h3 className="text-lg font-semibold mb-2">金融术语类型</h3>
        <div className="grid grid-cols-3 gap-2 mb-4">
          <label className="flex items-center">
            <input
              type="checkbox"
              name="tradeNum"
              checked={termTypes.tradeNum}
              onChange={handleTermTypeChange}
              className="mr-1"
            />
            交易号
          </label>
          <label className="flex items-center">
            <input
              type="checkbox"
              name="orderNum"
              checked={termTypes.orderNum}
              onChange={handleTermTypeChange}
              className="mr-1"
            />
            订单号
          </label>
          <label className="flex items-center">
            <input
              type="checkbox"
              name="lossAmount"
              checked={termTypes.lossAmount}
              onChange={handleTermTypeChange}
              className="mr-1"
            />
            资损金额
          </label>
          <label className="flex items-center">
            <input
              type="checkbox"
              name="bankCardNum"
              checked={termTypes.bankCardNum}
              onChange={handleTermTypeChange}
              className="mr-1"
            />
            银行卡号
          </label>
          <label className="flex items-center">
            <input
              type="checkbox"
              name="payChannel"
              checked={termTypes.payChannel}
              onChange={handleTermTypeChange}
              className="mr-1"
            />
            支付渠道
          </label>
          <label className="flex items-center">
            <input
              type="checkbox"
              name="victim"
              checked={termTypes.victim}
              onChange={handleTermTypeChange}
              className="mr-1"
            />
            受害人
          </label>
          <label className="flex items-center">
            <input
              type="checkbox"
              name="victimIdentity"
              checked={termTypes.victimIdentity}
              onChange={handleTermTypeChange}
              className="mr-1"
            />
            受害人身份
          </label>
          <label className="flex items-center">
            <input
              type="checkbox"
              name="suspect"
              checked={termTypes.suspect}
              onChange={handleTermTypeChange}
              className="mr-1"
            />
            嫌疑人
          </label>
          <label className="flex items-center">
            <input
              type="checkbox"
              name="caseCity"
              checked={termTypes.caseCity}
              onChange={handleTermTypeChange}
              className="mr-1"
            />
            案发城市
          </label>
          <label className="flex items-center">
            <input
              type="checkbox"
              name="caseTime"
              checked={termTypes.caseTime}
              onChange={handleTermTypeChange}
              className="mr-1"
            />
            案发时间
          </label>
          <label className="flex items-center">
            <input
              type="checkbox"
              name="casePlatform"
              checked={termTypes.casePlatform}
              onChange={handleTermTypeChange}
              className="mr-1"
            />
            涉案平台
          </label>
          <label className="flex items-center">
            <input
              type="checkbox"
              name="phoneNum"
              checked={termTypes.phoneNum}
              onChange={handleTermTypeChange}
              className="mr-1"
            />
            手机号
          </label>
          <label className="flex items-center">
            <input
              type="checkbox"
              name="allFinanceTerms"
              checked={termTypes.allFinanceTerms}
              onChange={handleTermTypeChange}
              className="mr-1"
            />
            所有金融术语
          </label>
        </div>

        <button
          onClick={handleSubmit}
          disabled={isLoading}
          className={`bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 ${isLoading ? 'opacity-50 cursor-not-allowed' : ''}`}
        >
          {isLoading ? '处理中...' : '识别实体'}
        </button>
      </div>
      {coloredResult && (
        <div className="bg-white shadow-md rounded-lg p-6 mb-6">
          <h2 className="text-xl font-semibold mb-4">识别结果</h2>
          <div 
            style={{
              lineHeight: '2.2',  // 增加行高
              wordBreak: 'break-word',
              wordSpacing: '2px', // 增加词间距
              display: 'flex',
              flexWrap: 'wrap',
              gap: '3px'         // Flex布局的间距
            }}
          >
            {coloredResult}
          </div>
        </div>
      )}
      {result && (
        <div className="bg-blue-100 border-l-4 border-blue-500 text-blue-700 p-4 mb-6" role="alert">
          <p className="font-bold">JSON 结果：</p>
          <pre>{result}</pre>
        </div>
      )}
      <div className="flex items-center text-yellow-700 bg-yellow-100 p-4 rounded-md">
        <AlertCircle className="mr-2" />
        <span>这是演示版本，用于金融文本的命名实体识别。支持识别企业、职位、金融产品和市场等实体。</span>
      </div>
    </div>
  );
};

export default FinanceNERPage; 